package controller;

import com.alibaba.fastjson.JSON;
import entity.User;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.UUID;

@WebServlet("/wx_login")
public class WxLoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        try {
            Properties props = new Properties();
            props.load(UserService.class.getClassLoader().getResourceAsStream("wx_config.properties"));
            String appId = props.getProperty("wx.AppID");
            String appSecret = props.getProperty("wx.AppSecret");


            //微信平台带过来的code
            String code = req.getParameter("code");


            //准备发送请求获取access_token
            String url ="https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid="+appId +
                    "&secret="+appSecret +
                    "&code="+code +
                    "&grant_type=authorization_code";

            //执行请求
            HashMap<String,String> access_token_info = execute(url);

            String accessToken = access_token_info.get("access_token");
            String openId = access_token_info.get("openId");


            url =  "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=" +accessToken+
                    "&openid="+ openId;

            //根据access_token获取这个用户的信息
            HashMap<String,String> userInfo = execute(url);

            //获取这个微信用户的openid
            String openid = userInfo.get("openid");

            //根据openId查询用户
            User user = userService.findByWxOpenId(openid);

            if(user == null){

                //第一次使用微信登录
                user = new User();
                user.setUsername(UUID.randomUUID().toString());
                user.setPassword("admin");
                user.setAge(0L);
                String gender = "1".equals(userInfo.get("sex"))?"1":"0";
                user.setGender(gender);
                user.setPic(userInfo.get("headimgurl"));
                user.setRealName(userInfo.get("nickname"));
                user.setWxOpenid(userInfo.get("openid"));

                //注册一个用户
                userService.register(user);

                //再次根据微信的openId去查询这个用户（这一次主要是获取这个用户的id）
                user = userService.findByWxOpenId(openid);

                HttpSession session = req.getSession();
                session.setAttribute("loginUser", user);

                //登录成功，去首页
                resp.sendRedirect("/html/home.jsp");

            }else {
                //之前使用微信登录过
                HttpSession session = req.getSession();
                session.setAttribute("loginUser", user);
                resp.sendRedirect("/html/home.jsp");
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 使用HttpClient发送请求
     * @param url
     * @return
     * @throws Exception
     */
    public HashMap<String,String>execute(String url) throws Exception {

        //创建一个Client实例
        CloseableHttpClient httpclient = HttpClients.createDefault();

        //创建Get请求
        HttpGet httpget = new HttpGet(url);

        //执行请求，获取结果集
        CloseableHttpResponse response = httpclient.execute(httpget);

        //获取响应体，把响应体转成JSON字符串
        String json = EntityUtils.toString(response.getEntity(),"utf8");

        //将JSON转换成Map
        HashMap<String,String> hashMap = JSON.parseObject(json, HashMap.class);

        return hashMap;
    }


}
